package com.hellobike.haxing.modules.supplier.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.address.service.ITCityService;
import com.hellobike.haxing.modules.address.service.ITProvinceService;
import com.hellobike.haxing.modules.address.util.Convert2KV;
import com.hellobike.haxing.modules.product.entity.Category;
import com.hellobike.haxing.modules.product.entity.Sku;
import com.hellobike.haxing.modules.product.entity.Spu;
import com.hellobike.haxing.modules.product.service.ICategoryService;
import com.hellobike.haxing.modules.product.service.ISkuService;
import com.hellobike.haxing.modules.product.service.ISpuService;
import com.hellobike.haxing.modules.purchase.service.ITPurchaseProService;
import com.hellobike.haxing.modules.supplier.entity.TSupplierClPro;
import com.hellobike.haxing.modules.supplier.entity.TSupplierClassification;
import com.hellobike.haxing.modules.supplier.entity.TSupplierInfo;
import com.hellobike.haxing.modules.supplier.entity.TSupplierInvoice;
import com.hellobike.haxing.modules.supplier.service.ITSupplierClProService;
import com.hellobike.haxing.modules.supplier.service.ITSupplierClassificationService;
import com.hellobike.haxing.modules.supplier.service.ITSupplierInfoService;
import com.hellobike.haxing.modules.supplier.service.ITSupplierInvoiceService;
import com.hellobike.haxing.modules.supplier.util.Convert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
 * @Description: t_supplier_classification
 * @Author: haxing-boot
 * @Date:   2020-01-14
 * @Version: V1.0
 */
@RestController
@RequestMapping("/supplierClassification/tSupplierClassification")
@Slf4j
public class TSupplierClassificationController extends BaseController<TSupplierClassification, ITSupplierClassificationService> {
	@Autowired
	private ITSupplierClassificationService tSupplierClassificationService;
	@Autowired
	private ITSupplierInvoiceService itSupplierInvoiceService;
	@Autowired
	private ITSupplierClProService tSupplierClProService;
	@Autowired
	private ISkuService skuService;
	@Autowired
	private ISpuService spuService;
	@Autowired
	private ITProvinceService tProvinceService;
	@Autowired
	private ITCityService tCityService;
	@Autowired
	private ICategoryService categoryService;
	@Autowired
	private ITSupplierInfoService tSupplierInfoService;
	@Autowired
	private ITPurchaseProService tPurchaseProService;
	/**
	 * 分页列表查询
	 *
	 * @param tSupplierClassification
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "t_supplier_classification-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(TSupplierClassification tSupplierClassification,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<TSupplierClassification> queryWrapper = QueryGenerator.initQueryWrapper(tSupplierClassification, req.getParameterMap());
		Page<TSupplierClassification> page = new Page<TSupplierClassification>(pageNo, pageSize);
		IPage<TSupplierClassification> pageList = tSupplierClassificationService.page(page, queryWrapper);
		if(pageList.getTotal()>0){
			pageList.getRecords().forEach(
					item -> {
						item.setProvince1(Convert.json2list(item.getProvince()));
						item.setCity1(Convert.json2list(item.getCity()));
						item.setFirstCategory1(Convert.json2list(item.getFirstCategory()));
						item.setSecondCategory1(Convert.json2list(item.getSecondCategory()));
						item.setThirdCategory1(Convert.json2list(item.getThirdCategory()));
						item.setWarehouse1(Convert.json2list(item.getWarehouse()));
						item.setCity2(tCityService.getTCitys(item.getCity1()));
						item.setThirdCategory2(tSupplierClassificationService.getCategoryNames(item.getThirdCategory1()));
					}
			);
		}
		return Result.ok(pageList);
	}

	/**
	 *   添加
	 *
	 * @param tSupplierClassification
	 * @return
	 */
	@AutoLog(value = "t_supplier_classification-添加",operateType=2)
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody TSupplierClassification tSupplierClassification) {
		tSupplierClassificationService.save(tSupplierClassification);
		TSupplierInvoice tSupplierInvoice = new TSupplierInvoice();
		tSupplierInvoice.setFirstCategory(tSupplierClassification.getFirstCategory());
		tSupplierInvoice.setSecondCategory(tSupplierClassification.getSecondCategory());
		tSupplierInvoice.setThirdCategory(tSupplierClassification.getThirdCategory());
		tSupplierInvoice.setSupplierInfoId(tSupplierClassification.getSupplierId());
		itSupplierInvoiceService.save(tSupplierInvoice);
		return Result.ok("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param tSupplierClassification
	 * @return
	 */
	@AutoLog(value = "t_supplier_classification-编辑",operateType=3)
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody TSupplierClassification tSupplierClassification) {
		tSupplierClassification.setProvince(Convert.list2Json(tSupplierClassification.getProvince1()));
		tSupplierClassification.setCity(Convert.list2Json(tSupplierClassification.getCity1()));
		tSupplierClassification.setFirstCategory(Convert.list2Json(tSupplierClassification.getFirstCategory1()));
		tSupplierClassification.setSecondCategory(Convert.list2Json(tSupplierClassification.getSecondCategory1()));
		tSupplierClassification.setThirdCategory(Convert.list2Json(tSupplierClassification.getThirdCategory1()));
		tSupplierClassification.setWarehouse(Convert.list2Json((tSupplierClassification.getWarehouse1())));
		tSupplierClassificationService.updateById(tSupplierClassification);

		// 更新商家信息中的仓库
		TSupplierInfo updateDo = new TSupplierInfo();
		updateDo.setCity(tSupplierClassificationService.getWareHouseNames(tSupplierClassification.getWarehouse1()));
		updateDo.setId(tSupplierClassification.getSupplierId());
		tSupplierInfoService.updateById(updateDo);

		// 生成分类商品详情
		QueryWrapper<TSupplierClPro> queryPro = new QueryWrapper<>();
		queryPro.eq("supplier_id", tSupplierClassification.getSupplierId());
		int resPro = tSupplierClProService.count(queryPro);
		if(resPro < 1){
			for(String third : tSupplierClassification.getThirdCategory1()) {
				setClp(third,tSupplierClassification);
			}
		}else{ // 如果已存在 对比更新
			List<TSupplierClPro> tsupplierClPros = tSupplierClProService.list(queryPro);
			List<String> isExistPro = new ArrayList<>();
			tsupplierClPros.forEach( // 删除原来没有的
					item -> {
						isExistPro.add(item.getThirdCategory());
						if(!tSupplierClassification.getThirdCategory1().contains(item.getThirdCategory())){
							QueryWrapper<TSupplierClPro> removeClpDo = new QueryWrapper<>();
							removeClpDo.eq("supplier_id", tSupplierClassification.getSupplierId());
							removeClpDo.eq("third_category", item.getThirdCategory());
							tSupplierClProService.remove(removeClpDo);

							QueryWrapper<TSupplierInvoice> removeInvoiceDo = new QueryWrapper<>();
							removeInvoiceDo.eq("supplier_info_id", tSupplierClassification.getSupplierId());
							removeInvoiceDo.eq("third_category", item.getThirdCategory());
							itSupplierInvoiceService.remove(removeInvoiceDo);
//
//							QueryWrapper<TPurchasePro> removeTPurchaseProDo = new QueryWrapper<>();
//							removeTPurchaseProDo.eq("sku_id", item.getSkuId());
//							tPurchaseProService.remove(removeTPurchaseProDo);
						}
					}
			);
			for(String third : tSupplierClassification.getThirdCategory1()){
//				if(!isExistPro.contains(third)){ // 添加原来没有的
					setClp(third,tSupplierClassification);
//				}
			}
		}

		return Result.ok("编辑成功!");
	}

	private void setClp(String third,TSupplierClassification tSupplierClassification){
		QueryWrapper<Spu> querySpus = new QueryWrapper<>();
		querySpus.eq("category_id3", third);
		List<Spu> spus = spuService.list(querySpus);
		if (spus != null && spus.size() > 0) {
			for(Spu spu : spus) {
				QueryWrapper<Sku> querySku = new QueryWrapper<>();
				querySku.eq("spu_id", spu.getId());
				List<Sku> skus = skuService.list(querySku);
				if(skus == null || skus.size() < 1){
					continue;
				}
				for(Sku sku : skus) {

					TSupplierClPro tspupplierClPro = new TSupplierClPro();
					tspupplierClPro.setFirstCategory(spu.getCategoryId1().toString());
					tspupplierClPro.setSecondCategory(spu.getCategoryId2().toString());
					tspupplierClPro.setThirdCategory(third);
					tspupplierClPro.setSupplierName(tSupplierClassification.getSupplierName());
					tspupplierClPro.setSkuId(sku.getId());
					tspupplierClPro.setSkuName(spu.getSpuName());
					tspupplierClPro.setSkuUnit(spu.getOrderSpecUnit());
					if (sku.getDimensionValues() != null) {
						tspupplierClPro.setDimensionValues(sku.getDimensionValues().toJSONString());
					}
					tspupplierClPro.setDeleted(0);
					tspupplierClPro.setSupplierId(tSupplierClassification.getSupplierId());
					tspupplierClPro.setDateDue(spu.getDateDue());
					tspupplierClPro.setDateProduce(spu.getDateProduce());

					// 如果有就更新商品数据
					QueryWrapper<TSupplierClPro> clpDo = new QueryWrapper<>();
					clpDo.eq("supplier_id", tSupplierClassification.getSupplierId());
					clpDo.eq("sku_id", sku.getId());
					TSupplierClPro res = tSupplierClProService.getOne(clpDo);
					if (res != null) {
						tspupplierClPro.setId(res.getId());
						tSupplierClProService.updateById(tspupplierClPro);
					}else {
						tSupplierClProService.save(tspupplierClPro);
					}
					//同步预备采购商品
					tPurchaseProService.syncProFromClp(tspupplierClPro);
				}

				// 生成发票税率
				tSupplierClassification.setFirstCategory(spu.getCategoryId1().toString());
				tSupplierClassification.setSecondCategory(spu.getCategoryId2().toString());
				setInvoice(third,tSupplierClassification);
			}
		}
	}

	private void setInvoice(String third, TSupplierClassification tSupplierClassification){
		QueryWrapper<TSupplierInvoice> query = new QueryWrapper<>();
		query.eq("supplier_info_id", tSupplierClassification.getSupplierId());
		query.eq("third_category", third);
		int res = itSupplierInvoiceService.count(query);
		if(res < 1 && tSupplierClassification.getThirdCategory1() != null){
			TSupplierInvoice tSupplierInvoice = new TSupplierInvoice();
			tSupplierInvoice.setSupplierInfoId(tSupplierClassification.getSupplierId());
			tSupplierInvoice.setFirstCategory(tSupplierClassification.getFirstCategory());
			tSupplierInvoice.setSecondCategory(tSupplierClassification.getSecondCategory());
			tSupplierInvoice.setThirdCategory(third);
			tSupplierInvoice.setDeleted(0);
			itSupplierInvoiceService.save(tSupplierInvoice);
		}
	}

	/**
	 * initProvince
	 *
	 * @return
	 */
	@PostMapping(value = "/initProvince")
	public Result<?> initProvince() {
		return Result.ok(tProvinceService.getAllProvinces());
	}


	/**
	 * initCity
	 *
	 * @return
	 */
	@PostMapping(value = "/initCity")
	public Result<?> initCity() {
		return Result.ok(tCityService.getAllCitys());
	}

	/**
	 * initFirstCategorys
	 *
	 * @return
	 */
	@PostMapping(value = "/initFirstCategorys")
	public Result<?> initFirstCategorys() {
		QueryWrapper<Category> query = new QueryWrapper<>();
		query.eq("level", 1l);
		List<Category> categories = categoryService.list(query);
		return Result.ok(Convert2KV.Category2kv(categories));
	}

	/**
	 * initSecondCategorys
	 *
	 * @return
	 */
	@PostMapping(value = "/initSecondCategorys")
	public Result<?> initSecondCategorys() {
		QueryWrapper<Category> query = new QueryWrapper<>();
		query.eq("level", 2l);
		List<Category> categories = categoryService.list(query);
		return Result.ok(Convert2KV.Category2kv(categories));	 }

	/**
	 * initThirdCategorys
	 *
	 * @return
	 */
	@PostMapping(value = "/initThirdCategorys")
	public Result<?> initThirdCategorys() {
		QueryWrapper<Category> query = new QueryWrapper<>();
		query.eq("level", 3l);
		List<Category> categories = categoryService.list(query);
		return Result.ok(Convert2KV.Category2kv(categories));	 }

	/**
	 * initThirdCategorys
	 *
	 * @return
	 */
	@PostMapping(value = "/initWarehouses")
	public Result<?> initWarehouses() {
		return Result.ok(tSupplierClassificationService.getWareHouse(null));	 }

	/**
	 * getCity
	 *
	 * @return
	 */
	@PostMapping(value = "/getCity")
	public Result<?> getCity(@RequestBody JSONObject json) {
		String headerId = json.getString("headerId");
		headerId = headerId.replace("[","");
		headerId = headerId.replace("]","");
		String[] idArr = headerId.split(",");
		return Result.ok(tCityService.getTCitys4List(Arrays.asList(idArr)));
	}

	/**
	 * getWareHouse
	 *
	 * @return
	 */
	@PostMapping(value = "/getWareHouse")
	public Result<?> getWareHouse(@RequestBody JSONObject json) {
		String headerId = json.getString("headerId");
		headerId = headerId.replace("[","");
		headerId = headerId.replace("]","");
		String[] idArr = headerId.split(",");
		return Result.ok(tSupplierClassificationService.getWareHouse(Arrays.asList(idArr)));
	}
	@PostMapping(value = "/getSupplier")
	public Result<?> getSupplier(@RequestBody JSONObject json) {
		String headerId = json.getString("headerId");
		headerId = headerId.replace("[","");
		headerId = headerId.replace("]","");
		String[] idArr = headerId.split(",");
		System.out.print(idArr);
		return Result.ok(tSupplierClassificationService.getSupplierInfoByWarehouseIds(headerId));
	}

	/**
	 * getSecondCategory
	 *
	 * @return
	 */
	@PostMapping(value = "/getCategory")
	public Result<?> getCategory(@RequestBody JSONObject json) {
		String headerId = json.getString("headerId");
		headerId = headerId.replace("[","");
		headerId = headerId.replace("]","");
		String[] idArr = headerId.split(",");
		return Result.ok(tSupplierClassificationService.getCategorys(Arrays.asList(idArr)));
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "t_supplier_classification-删除",operateType=4)
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) Long id) {
		tSupplierClassificationService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "t_supplier_classification-批量删除",operateType=4)
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tSupplierClassificationService.removeByIds(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) Long id) {
		TSupplierClassification tSupplierClassification = tSupplierClassificationService.getById(id);
		if(tSupplierClassification==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(tSupplierClassification);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param tSupplierClassification
	 */
	@AutoLog(value = "t_supplier_classification-导出excel",operateType=6)
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, TSupplierClassification tSupplierClassification) {
		return super.exportXls(request, tSupplierClassification, TSupplierClassification.class, "t_supplier_classification");
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@AutoLog(value = "t_supplier_classification-导入excel",operateType=5)
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, TSupplierClassification.class);
	}

}
